#!/usr/bin/env python


class Summary:
  @staticmethod
  def commits(repo, since, until):
    """Summary of commits, count of insertions and deletions"""
    count = 0
    insertions = 0
    deletions = 0
    
    for c in repo.iter_commits(since=since, until=until):
      stats = c.stats.total
      
      count += 1
      insertions += stats["insertions"]
      deletions += stats["deletions"]
      
    return {
      "count": count,
      "ins": insertions,
      "del": deletions
    }
    
  @staticmethod
  def developers(repo, since, until):
    """Summary of developers, count and most active developers"""
    developers = {}
    
    for c in repo.iter_commits(since=since, until=until):
      stats = c.stats.total
      name = c.committer.name
      
      if not name in developers:
        developers[name] = {
          "commits": 0,
          "ins": 0,
          "del": 0
        }
      
      developers[name]["commits"] += 1
      developers[name]["ins"] += stats["insertions"]
      developers[name]["del"] += stats["deletions"]
      
    count = len(developers)
    
    # Choose 5 most active developers
    num = 5
    names = developers.keys()
    names.sort(key=lambda x: developers[x]["commits"], reverse=True)
    developers = map(lambda n: (n, developers[n]), names[:num])
    
    return {"count": count, "developers": developers}
    
  @staticmethod
  def files(repo, since, until):
    """Summary of most modified files"""
    count = {}
    
    for c in repo.iter_commits(since=since, until=until):
      files = c.stats.files
      for f in files.keys():
        if not f in count:
          count[f] = {"edited": 0, "lines": 0}
        count[f]["edited"] += 1
        count[f]["lines"] += files[f]["lines"]
    
    # Choose 5 most edited files
    num = 5
    most_edited = sorted(count, key=lambda f: count[f]["edited"], reverse=True)[:num]
    most_lines = sorted(count, key=lambda f: count[f]["lines"], reverse=True)[:num]
    
    return {
      "most_edited": map(lambda f: (f, count[f]["edited"]), most_edited),
      "most_lines": map(lambda f: (f, count[f]["lines"]), most_lines)
    }
